/*
 */
package aptech.eproject.logictics.dao.kien;

import aptech.eproject.logictics.db.Account;
import aptech.eproject.logictics.db.Customer;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Kien Nguyen <solidfoxrock at gmail.com>
 */
@Stateless
public class LoginService implements LoginServiceRemote {

    @PersistenceContext
    private EntityManager em;

    /**
     * Check whether account is blocked or not
     * @param userName
     * @return return true if account is existed and is blocked
     */
    public boolean isBlocked(String userName) {
        Account account = em.find(Account.class, userName);
        if (account != null) {
            return account.getIsBlocked();
        } else {
            Customer customer = em.find(Customer.class, userName);
            if (customer != null) {
                return customer.getIsBlocked();
            }
        }
        return false;
    }

    /**
     * Get the password of an username
     * @param userName
     * @return null 
     *  if the username does not exist in both Account and Customer table or it is blocked
     */
    public String getPassword(String userName) {

        String password = null;

        // find account first
        Account account = em.find(Account.class, userName);
        if (account != null && !account.getIsBlocked()) {
            password = account.getPassword();
        } else {
            // account not exist, then find customer
            Customer customer = em.find(Customer.class, userName);
            if (customer != null && !customer.getIsBlocked()) {
                password = customer.getPassword();
            }
        }
        return password;
    }

    /**
     * Get role name of an Account's username
     * @param userName
     * @return null if the userName is not existed, 
     * "Customer" if the userName is a customer, else return the Account role
     */
    public String getRole(String userName) {

        Account account = em.find(Account.class, userName);
        if (account != null) {
            return account.getRole().toString();
        } else {
            Customer customer = em.find(Customer.class, userName);
            if (customer != null) {
                return "Customer";
            }
        }
        return null;
    }

}
